package com.qingdai.securityauth.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qingdai.business.emuns.User;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.business.service.UserService;
import com.qingdai.business.utils.JwtUtil;
import com.qingdai.business.utils.WebUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private JwtUtil jwtUtil;
    @DubboReference
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try {
            org.springframework.security.core.userdetails.User userDetail =
                    (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
            Collection<GrantedAuthority> authorities = userDetail.getAuthorities();
            User user = userService.getUserByUsername(userDetail.getUsername());
            Integer userId = user.getId();
            Map userInfo = new HashMap<>();
            userInfo.put("userId", userId);
            userInfo.put("Authorities", authorities);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            CommonResult jwtObject = jwtUtil.createJWT(uuid, null, 1000 * 60 * 60 * 24, userInfo);
            String jwt = jwtObject.getData().toString();
            CommonResult result = new CommonResult<>(200, "登陆成功", jwt);
            String responseJson = JSON.toJSONString(result);
            redisTemplate.opsForValue().set("loginToken-UserId:" + userId, jwt, 60 * 60 * 24, TimeUnit.SECONDS);
            WebUtil.renderString(response, responseJson);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
